package com.cyys.modules.core.controller;

import com.cyys.common.ql.BaseReturn;
import com.cyys.modules.core.shiro.token.manage.TokenManager;
import com.cyys.modules.system.model.user.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Action超类 提供session request response ajax支持
 *
 * @author LC
 *
 */
public class BaseAction extends BaseReturn {

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	protected HttpSession session;

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession(true);
	}

	/**
	 * 添加Model消息
	 *
	 * @param model
	 */
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages) {
			sb.append(message).append(messages.length > 1 ? "<br/>" : "");
		}
		model.addAttribute("message", sb.toString());
	}

	protected User getUser() {
		return TokenManager.getToken();
	}

	/**
	 * 是否系统开发人员
	 * @return
	 */
	protected Boolean isSystemDeveloper() {
		return getUser().getId().equals("1") ? true : false;
	}

	protected ServletContext getServletContext() {
		return request.getSession().getServletContext();
	}

	/**
	 * @description: 返回的数据
	 * @param code 自定义返回的状态码
	 * @param msg 消息
	 * @return ${return_type}
	 * @throws
	 * @author lishengquan
	 * @date 2019/6/10 10:19
	 * @version 1.0
	 */
	protected Map<String, Object> result(Integer code, String msg){
		Map<String, Object> map = new HashMap<>(16);
		map.put("code", code);
		map.put("msg", msg);
		return map;
	}

	@InitBinder
	protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}
}
